'use client';

import {
  getCategoryByPaths,
  parseSearchParams,
  searchParamsToFilters,
} from '@/utils/common';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { useGlobalState } from './useGlobalState';

export function useClientParams() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const categoryList = useGlobalState('product', 'categoryList');

  //===================================================
  const initQuery = Object.fromEntries(searchParams);
  const [queryObject, setQueryObject] = useState<Obj>(initQuery);
  const [filterObject, setFilterObject] = useState<Obj>(
    searchParamsToFilters(initQuery, categoryList)
  );
  const [paramsObject, setParamsObject] = useState<Obj>(
    parseSearchParams(initQuery)
  );
  const onSearchChange = () => {
    const query = Object.fromEntries(searchParams);
    JSON.stringify(queryObject) != JSON.stringify(query) &&
      setQueryObject(query);
    const filters = searchParamsToFilters(query, categoryList);
    JSON.stringify(filterObject) != JSON.stringify(filters) &&
      setFilterObject(filters);
    const params = parseSearchParams(query);
    JSON.stringify(paramsObject) != JSON.stringify(params) &&
      setParamsObject(params);
  };
  const onSearchChangeRef = useRef(onSearchChange);
  onSearchChangeRef.current = onSearchChange;
  useEffect(() => {
    onSearchChangeRef.current();
  }, [searchParams]);
  //===================================================
  const initPaths = pathname
    .split('/')
    .map((p: any) => p.replace(/\.html?$/i, ''));

  let initBasePath = initPaths.length > 1 ? initPaths[1] : '';
  initBasePath =
    initBasePath == 'categories' &&
    initPaths.length > 2 &&
    initPaths[2] == 'new-arrivals'
      ? 'new-arrivals'
      : initBasePath;
  const [basePath, setBasePath] = useState<string>(initBasePath);
  const initPathStartNum =
    initBasePath == 'catalogsearch' ||
    pathname.match('/categories/new-arrivals')
      ? 3
      : 2;

  const [catePaths, setCatePaths] = useState<string[]>(
    initPaths.length > initPathStartNum ? initPaths.slice(initPathStartNum) : []
  );
  const initCate = getCategoryByPaths(
    initPaths.slice(initPathStartNum),
    categoryList
  );
  const [categoryObject, setCategoryObject] = useState<Category | null>(
    initCate
  );
  const onPathsChange = () => {
    const pathsArray = pathname
      .split('/')
      .map((p: any) => p.replace(/\.html?$/i, ''));
    let thisBasePath = '',
      pathStartNum = 2;
    if (pathsArray.length > 1) {
      if (
        pathsArray.length > 2 &&
        pathsArray[1] === 'categories' &&
        pathsArray[2] === 'new-arrivals'
      ) {
        setBasePath(pathsArray[2]);
        thisBasePath = pathsArray[2];
      } else {
        setBasePath(pathsArray[1]);
        thisBasePath = pathsArray[1];
      }
    } else {
      setBasePath('');
    }
    pathStartNum =
      thisBasePath == 'catalogsearch' ||
      pathname.match('/categories/new-arrivals')
        ? 3
        : 2;
    if (pathsArray.length > pathStartNum) {
      const paths = pathsArray.slice(pathStartNum);
      catePaths.toString() != paths.toString() && setCatePaths(paths);
      const currCate = getCategoryByPaths(paths, categoryList);
      setCategoryObject(currCate);
    } else {
      catePaths?.length > 0 && setCatePaths([]);
      categoryObject != null && setCategoryObject(null);
    }
  };
  const onPathsChangeRef = useRef(onPathsChange);
  onPathsChangeRef.current = onPathsChange;
  useEffect(() => {
    onPathsChangeRef.current();
  }, [pathname]);

  return {
    router,
    pathname,
    searchParams,
    queryObject,
    filterObject,
    categoryObject,
    paramsObject,
    basePath,
    catePaths,
    categoryList,
  };
}
